/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the 'License');
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an 'AS IS' BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Copyright (c) 2025, Huawei Technologies.
Adapt to the model hierarchical visualization data collected by the msprobe tool
==============================================================================*/
import { Notification } from '@vaadin/notification';
import * as d3 from 'd3';
import * as _ from 'lodash';
import * as tf_graph_common from './common';
import { Class, FontSizeInPx, selectChild, selectOrCreateChild } from './common';
import * as contextmenu from './contextmenu';
import * as tf_graph from './graph';
import { MetanodeImpl, NodeType, OpNodeImpl } from './graph';
import * as layout from './layout';
import * as render from './render';
import * as tf_graph_scene from './scene';
import { TfGraphScene } from './tf-graph-scene';
import * as tf_graph_util from './util';

/**
 * Select or Create a 'g.nodes' group to a given sceneGroup
 * and builds a number of 'g.node' groups inside the group.
 *
 * Structure Pattern:
 *
 * <g class='nodes'>
 *   <g class='node'>
 *     <g class='in-annotations'>
 *       ...
 *     </g>
 *     <g class='out-annotations'>
 *       ...
 *     </g>
 *     <g class='nodeshape'>
 *      <!--
 *      Content of the node shape should be for the node itself. For example a
 *      Metanode would have a <rect> with rounded edges, an op would have an
 *      <ellipse>. More complex nodes like series may contain multiple
 *      elements which are conditionally visible based on whether the node is
 *      expanded.
 *      -->
 *     </g>
 *     <text class='label'>node name</text>
 *     <g class='subscene'>
 *       <!--
 *       Content of  the subscene (only for metanode and series node).
 *
 *       Subscene is a svg group that contains content of the
 *       metanode's metagraph that is recursively generated by Scene.build().
 *
 *       When the graph is expanded multiple times, a subscene can contain
 *       nested subscenes inside.
 *       -->
 *     </g>
 *   </g>
 *   ...
 * </g>
 *
 *
 * @param sceneGroup selection of the container
 * @param nodeData array of render node information to map
 * @param sceneElement <tf-graph-scene> polymer element
 * @return selection of the created nodeGroups
 */
let colorStorage: { [key: string]: string } = {};
export function buildGroup(sceneGroup, nodeData: render.RenderNodeInfo[], sceneElement): void {
  let container = tf_graph_common.selectOrCreateChild(sceneGroup, 'g', Class.Node.CONTAINER);
  // Select all children and join with data.
  // (Note that all children of g.nodes are g.node)
  let nodeGroups = (container as any)
    .selectAll(function () {
      return this.childNodes;
    })
    .data(nodeData, (d) => {
      // make sure that we don't have to swap shape type
      return `${d.node.name}:${d.node.type}`;
    });
  // ENTER
  nodeGroups
    .enter()
    .append('g')
    .attr('data-name', (d) => {
      return d.node.name;
    })
    .each(function (d) {
      let nodeGroup = d3.select(this);
      // index node group for quick stylizing
      sceneElement.addNodeGroup(d.node.name, nodeGroup);
    })
    .merge(nodeGroups)
    // ENTER + UPDATE
    .attr('class', (d: render.RenderNodeInfo) => {
      return `${Class.Node.GROUP} ${nodeClass(d)}`;
    })
    .each(function (d: render.RenderNodeInfo) {
      let nodeGroup = d3.select(this);
      // Build .shape first (background of the node).
      let shape = buildShape(nodeGroup, d, Class.Node.SHAPE);
      let shape1 = buildShape(nodeGroup, d, Class.Node.OUTER);
      if (d.node.isGroupNode) {
        addButton(shape, d, sceneElement);
      }
      if (d.node.isGroupNode) {
        addButton(shape1, d, sceneElement);
      }
      addInteraction(shape, d, sceneElement);
      addInteraction(shape1, d, sceneElement);
      // Build subscene on the top.
      subsceneBuild(nodeGroup, <render.RenderGroupNodeInfo>d, sceneElement);
      // Build label last. Should be on top of everything else.
      let label = labelBuild(nodeGroup, d, sceneElement);
      // Do not add interaction to metanode labels as they live inside the
      // metanode shape which already has the same interactions.
      addInteraction(label, d, sceneElement, d.node.type === NodeType.META);
      stylize(nodeGroup, d, sceneElement);
      position(nodeGroup, d);
    });
  // EXIT
  nodeGroups
    .exit()
    .each(function (d) {
      // remove all indices on remove
      sceneElement.removeNodeGroup(d.node.name);
    })
    .remove();
}
/**
 * Update or remove the subscene of a render group node depending on whether it
 * is a expanded. If the node is not a group node, this method has no effect.
 *
 * @param nodeGroup selection of the container
 * @param renderNodeInfo the render information for the node.
 * @param sceneElement <tf-graph-scene> polymer element.
 * @return Selection of the subscene group, or null if node group does not have
 *        a subscene. Op nodes, bridge nodes and unexpanded group nodes will
 *        not have a subscene.
 */
function subsceneBuild(nodeGroup, renderNodeInfo: render.RenderGroupNodeInfo, sceneElement: TfGraphScene): void {
  if (renderNodeInfo.node.isGroupNode) {
    if (renderNodeInfo.expanded) {
      // Recursively build the subscene.
      buildGroupForScene(nodeGroup, renderNodeInfo, sceneElement, Class.Subscene.GROUP);
      return;
    }
    // Clean out existing subscene if the node is not expanded.
    tf_graph_scene.selectChild(nodeGroup, 'g', Class.Subscene.GROUP).remove();
  }
}
/**
 * Translate the subscene of the given node group
 */
function subscenePosition(nodeGroup, d: render.RenderNodeInfo): void {
  // Translate the subscene to the middle of the parent node in vertical direction.
  let x0 = d.x - (d.coreBox.width / 2);
  let y0 = d.y - (d.height / 2) + d.paddingTop;
  let subscene = tf_graph_scene.selectChild(nodeGroup, 'g', Class.Subscene.GROUP);
  tf_graph_scene.translate(subscene, x0, y0);
}
/**
 * Add an expand/collapse button to a group node
 *
 * @param selection The group node selection.
 * @param d Info about the node being rendered.
 * @param sceneElement <tf-graph-scene> polymer element.
 */
function addButton(selection, d: render.RenderNodeInfo, sceneElement): void {
  let group = tf_graph_common.selectOrCreateChild(selection, 'g', Class.Node.BUTTON_CONTAINER);
  tf_graph_common.selectOrCreateChild(group, 'circle', Class.Node.BUTTON_CIRCLE);
  tf_graph_common.selectOrCreateChild(group, 'path', Class.Node.EXPAND_BUTTON).attr('d', 'M0,-2.2 V2.2 M-2.2,0 H2.2');
  tf_graph_common.selectOrCreateChild(group, 'path', Class.Node.COLLAPSE_BUTTON).attr('d', 'M-2.2,0 H2.2');
  (group as any).on('click', (dGroup: any) => {
    // Stop this event's propagation so that it isn't also considered a
    // node-select.
    (<Event>d3.event).stopPropagation();
    sceneElement.fire('node-toggle-expand', { name: dGroup.node.name });
  });
  tf_graph_scene.positionButton(group, d);
}
/**
 * Fire node-* events when the selection is interacted.
 *
 * @param disableInteraction When true, have the provided selection
 * ignore all pointer events. Used for text labels inside of metanodes, which
 * don't need interaction as their surrounding shape has interaction, and if
 * given interaction would cause conflicts with the expand/collapse button.
 */
function addInteraction(
  selection,
  d: render.RenderNodeInfo,
  sceneElement: TfGraphScene,
  disableInteraction?: boolean,
): void {
  if (disableInteraction) {
    selection.attr('pointer-events', 'none');
    return;
  }
  let contextMenuFunction = contextmenu.getMenu(sceneElement, d);
  let time = 0;
  let timeOut;
  let mouseMoved = false;
  let startX;
  let startY;
  const movementThreshold = 5;
  selection
    .on('dblclick', (dDbClick) => {
      clearTimeout(timeOut);
      sceneElement.fire('node-toggle-expand', { name: dDbClick.node.name });
    })
    .on('mouseover', (dMouseover) => {
      // don't send mouseover over expanded group,
      // otherwise it is causing too much glitches
      if (sceneElement.isNodeExpanded(dMouseover)) {
        return;
      }
      sceneElement.fire('node-highlight', { name: dMouseover.node.name });
    })
    .on('mouseout', (dMouseOut) => {
      // don't send mouseover over expanded group,
      // otherwise it is causing too much glitches
      if (sceneElement.isNodeExpanded(dMouseOut)) {
        return;
      }
      sceneElement.fire('node-unhighlight', { name: dMouseOut.node.name });
    })
    .on('mousedown', () => {
      startX = d3.event.clientX;
      startY = d3.event.clientY;
      mouseMoved = false; // 重置标志变量
    })

    // 监听鼠标抬起事件，检查是否超过浮动阈值
    .on('mouseup', () => {
      const deltaX = Math.abs(d3.event.clientX - startX);
      const deltaY = Math.abs(d3.event.clientY - startY);
      if (deltaX > movementThreshold || deltaY > movementThreshold) {
        mouseMoved = true;
      }
    })

    .on('click', (dClick) => {
      clearTimeout(timeOut); // 清除第一个单击事件
      if (mouseMoved) {
        mouseMoved = false; // 重置标志变量
        return;
      }
      timeOut = setTimeout(() => {
        sceneElement.fire('node-select', { name: dClick.node.name });
        sceneElement.fire('no-pan-to-node', {});
      }, time);
    })

    .on('contextmenu', (dCtx, i) => {
      sceneElement.fire('node-select', { name: dCtx.node.name });
      contextMenuFunction.call(dCtx, i);
    });
}

/**
 * Append svg text for label and assign data.
 * @param nodeGroup
 * @param renderNodeInfo The render node information for the label.
 * @param sceneElement <tf-graph-scene> polymer element.
 */
function labelBuild(nodeGroup, renderNodeInfo: render.RenderNodeInfo, sceneElement): d3.Selection<any, any, any, any> {
  let text = renderNodeInfo.displayName;
  // Truncate long labels for unexpanded Metanodes.
  let useFontScale =
    renderNodeInfo.node.type === (NodeType.META || NodeType.MULTI_COLLECTION || NodeType.API_LIST) &&
    !renderNodeInfo.expanded;
  let label = tf_graph_common.selectOrCreateChild(nodeGroup, 'text', Class.Node.LABEL);
  // Make sure the label is visually on top among its siblings.
  let labelNode = <HTMLElement>label.node();
  labelNode.parentNode?.appendChild(labelNode);
  label.attr('dy', '.35em').attr('text-anchor', 'middle');

  // In tf-graph-scene styles, fontSizes are defined to vary from 6px to 9px. Since we
  // do not want to invoke computedStyles or hardcode the fontSize that would be
  // duplicated in styles, we are rounding it to 8px which does not cause any visible
  // jank.
  let fontSize = 8;

  switch (renderNodeInfo.node.type) {
    case NodeType.META:
    case NodeType.MULTI_COLLECTION:
    case NodeType.API_LIST:
      fontSize = renderNodeInfo.expanded ? FontSizeInPx.Node.EXPANDED_LABEL : FontSizeInPx.Node.SERIES_LABEL;
      break;
    case NodeType.OP:
      fontSize = FontSizeInPx.Node.OP_LABEL;
      break;
    default:
      break;
  }

  if (useFontScale) {
    if (text.length > sceneElement.maxMetanodeLabelLength) {
      text = `${text.substr(0, sceneElement.maxMetanodeLabelLength - 2)}…`;
    }
    let scale = getLabelFontScale(sceneElement);
    label.attr('font-size', `${scale(text.length)}px`);
    fontSize = scale(text.length);
  }
  let txtElement = <d3.Selection<any, any, any, any>>label.text(text);
  enforceLabelWidth(txtElement, renderNodeInfo.node.type, fontSize, renderNodeInfo);
  return label;
}

/**
 * This function shortens text which would exceed the maximum pixel width of
 * a label.
 *
 * @param txtElementSelection The text element containing the label's text as d3
 * selection.
 * @param nodeType The type of the node the label belongs to. If the node is
 * an annotation, the value is -1. Label widths are defined in
 * layout.PARAMS.nodeSize.{meta|op|...}.maxLabelWidth for nodes and
 * layout.PARAMS.annotations.labelWidth for annotations.
 * @param renderNodeInfo The render information about the node, required to
 * determine whether META nodes are collapsed or expanded.
 */
export function enforceLabelWidth(
  txtElementSelection: d3.Selection<any, any, any, any>,
  nodeType: NodeType | number,
  fontSize: number,
  renderNodeInfo?: render.RenderNodeInfo,
): void {
  // Get text element itself and its on-screen width.
  let txtNode = <SVGTextElement>txtElementSelection.node();
  let labelContent = txtNode.textContent;

  // Get maximum length from settings.
  let maxLength: number | null = null;
  switch (nodeType) {
    case NodeType.META:
    case NodeType.MULTI_COLLECTION:
    case NodeType.API_LIST:
      if (renderNodeInfo && !renderNodeInfo.expanded) {
        // Only trim text if
        // node expanded.
        maxLength = layout.PARAMS.nodeSize.meta.maxLabelWidth;
      }
      break;
    case NodeType.OP:
      maxLength = layout.PARAMS.nodeSize.op.maxLabelWidth;
      break;
    case -1:
      maxLength = layout.PARAMS.annotations.maxLabelWidth;
      break;
    default:
      break;
  }
  if (maxLength === null) {
    return;
  }

  txtNode.textContent = tf_graph_util.maybeTruncateString(txtNode.textContent ?? '', fontSize, maxLength);
  // Add tooltip with full name and return.
  txtElementSelection.append('title').text(labelContent);
}
/**
 * d3 scale used for sizing font of labels, used by labelBuild,
 * initialized once by getLabelFontScale.
 */
let fontScale: any = null;
function getLabelFontScale(sceneElement): any {
  if (!fontScale) {
    fontScale = d3
      .scaleLinear()
      .domain([sceneElement.maxMetanodeLabelLengthLargeFont, sceneElement.maxMetanodeLabelLength])
      .range([sceneElement.maxMetanodeLabelLengthFontSize, sceneElement.minMetanodeLabelLengthFontSize])
      .clamp(true);
  }
  return fontScale;
}
/**
 * Set label position of a given node group
 */
function labelPosition(nodeGroup, cx: number, cy: number, yOffset: number): void {
  tf_graph_scene
    .selectChild(nodeGroup, 'text', Class.Node.LABEL)
    .transition()
    .attr('x', cx)
    .attr('y', cy + yOffset);
}
/**
 * Select or append/insert shape for a node and assign renderNode
 * as the shape's data.
 *
 * @param nodeGroup
 * @param d Render node information.
 * @param nodeClass class for the element.
 * @return Selection of the shape.
 */
export function buildShape(nodeGroup, d, nodeClassName: string): d3.Selection<any, any, any, any> {
  // Create a group to house the underlying visual elements.
  let shapeGroup = tf_graph_common.selectOrCreateChild(nodeGroup, 'g', nodeClassName);
  switch (d.node.type) {
    case NodeType.OP: {
      tf_graph_common.selectOrCreateChild(shapeGroup, 'ellipse', Class.Node.COLOR_TARGET);
      break;
    }
    case NodeType.META:
    case NodeType.MULTI_COLLECTION:
    case NodeType.API_LIST:
      tf_graph_common
        .selectOrCreateChild(shapeGroup, 'rect', Class.Node.COLOR_TARGET)
        .attr('rx', d.radius)
        .attr('ry', d.radius);
      break;
    default:
      throw Error(`Unrecognized node type: ${d.node.type}`);
  }
  return shapeGroup;
}
export function nodeClass(d: render.RenderNodeInfo): string {
  switch (d.node.type) {
    case NodeType.OP:
      return Class.OPNODE;
    case NodeType.META:
      return Class.METANODE;
    case NodeType.MULTI_COLLECTION:
      return Class.MULTI_COLLECTION;
    case NodeType.API_LIST:
      return Class.API_LIST;
    default:
      return '';
  }
}
/** Modify node and its subscene and its label's positional attributes */
function position(nodeGroup, d: render.RenderNodeInfo): void {
  let shapeGroup = tf_graph_scene.selectChild(nodeGroup, 'g', Class.Node.SHAPE);
  let shapeGroupHeader = tf_graph_scene.selectChild(nodeGroup, 'g', Class.Node.OUTER);
  let cx = layout.computeCXPositionOfNodeShape(d);
  switch (d.node.type) {
    case NodeType.OP: {
      // position shape
      let shape = tf_graph_scene.selectChild(shapeGroup, 'ellipse');
      tf_graph_scene.positionEllipse(shape, cx, d.y, d.coreBox.width, d.coreBox.height);
      labelPosition(nodeGroup, cx, d.y, d.labelOffset);
      break;
    }
    case NodeType.META: {
      // position shape
      let shapes = shapeGroup.selectAll('rect');
      let INSIDE_RECT_OFFSET = 0;
      // y值为定位值 取值为（15(色块高度)/2 (中心点y值) + 0.6 (向下偏移值, 不偏移会覆盖边及其颜色)）得出
      // 偏移值为8.1
      let OFFSET_VALUE = 8.1;
      if (d.expanded) {
        tf_graph_scene.positionRect(shapes, d.x, d.y, d.width, d.height);
        INSIDE_RECT_OFFSET = d.y - (d.height / 2) + OFFSET_VALUE;
        subscenePosition(nodeGroup, d);
        // Put the label on top.
        labelPosition(nodeGroup, cx, d.y, (-d.height / 2) + (d.labelHeight / 2));
      } else {
        tf_graph_scene.positionRect(shapes, cx, d.y, d.coreBox.width, d.coreBox.height);
        // Place the label in the middle.
        labelPosition(nodeGroup, cx, d.y, 0);
      }
      let shapesHeader = shapeGroupHeader.selectAll('rect');
      if (d.expanded) {
        tf_graph_scene.positionRect(shapesHeader, d.x, INSIDE_RECT_OFFSET, d.width - 1, 15);
        subscenePosition(nodeGroup, d);
        // Put the label on top.
        labelPosition(nodeGroup, cx, d.y, (-d.height / 2) + (d.labelHeight / 2));
      } else {
        tf_graph_scene.positionRect(shapesHeader, cx, d.y, d.coreBox.width, d.coreBox.height);
        // Place the label in the middle.
        labelPosition(nodeGroup, cx, d.y, 0);
      }
      break;
    }
    case NodeType.MULTI_COLLECTION:
    case NodeType.API_LIST: {
      // position shape
      let shapes = shapeGroup.selectAll('rect');
      if (d.expanded) {
        tf_graph_scene.positionRect(shapes, d.x, d.y, d.width, d.height);
        subscenePosition(nodeGroup, d);
        // Put the label on top.
        labelPosition(nodeGroup, cx, d.y, (-d.height / 2) + (d.labelHeight / 2));
      } else {
        tf_graph_scene.positionRect(shapes, cx, d.y, d.coreBox.width, d.coreBox.height);
        // Place the label in the middle.
        labelPosition(nodeGroup, cx, d.y, 0);
      }
      break;
    }
    default: {
      throw Error(`Unrecognized node type: ${d.node.type}`);
    }
  }
}

export function removeGradientDefinitions(svgRoot: SVGElement): void {
  d3.select(svgRoot).select('defs#_graph-gradients').remove();
}

export function getColorByPrecisionIndex(precisionStr: string): string {
  if (['medium', 'high', 'critical'].includes(precisionStr)) {
    switch (precisionStr) {
      case 'medium':
        return '#B6C7FC';
      case 'high':
        return '#7E96F0';
      case 'critical':
        return '#4668B8';
      default:
        break;
    }
  }
  const precision = Number(precisionStr);
  if (isNaN(precision)) {
    return 'white';
  }
  if (Object.entries(colorStorage).length !== 0) {
    for (const [color, details] of Object.entries(colorStorage)) {
      const detailsArray: any[] = [details];
      const [start, end] = detailsArray[0].value;
      // 进入md5模式
      const isPrecisionInRange = precision >= start && precision < end;
      const isPrecisionAtEnd = precision === end && end === 1;
      if (start === end) {
        if (precision === start) {
          return color;
        }
      } else if (isPrecisionInRange || isPrecisionAtEnd) {
        // 其他区间模式, 最后一个区间的右侧一定为1，所以特化precision == 1的情况
        return color;
      }
    }
    return 'white';
  } else {
    const colorMap = [
      { precision: 0.2, color: '#ff704d' },
      { precision: 0.4, color: '#FFC62E' },
      { precision: 0.6, color: '#FFDC7F' },
      { precision: 0.8, color: '#FFEDBE' },
      { precision: 1, color: '#FFFCF3' },
    ];
    for (const range of colorMap) {
      if (precision <= range.precision) {
        return range.color;
      }
    }
    return 'white';
  }
}
/**
 * Returns the fill color for the node given its state and the 'color by'
 * option.
 * Takes in optional svgRoot, when passed, that populates SVG definitions
 * for the fill inside the svgRoot when necessary.
 */
export function getFillForNode(renderInfo: render.RenderNodeInfo): string {
  if (renderInfo.node instanceof OpNodeImpl || renderInfo.node instanceof MetanodeImpl) {
    const precisionItem = renderInfo.node.attr.find((item) => item.key === tf_graph.PRECISION_INDEX);
    const overflowLevelItem = renderInfo.node.attr.find((item) => item.key === tf_graph.OVERFLOW_LEVEL);
    const matchedNodeLink = renderInfo.node.matchedNodeLink; // 标杆侧没有任何颜色
    // 以前缀来判断是单图节点还是对比图节点
    if (
      renderInfo.node.name.startsWith(tf_graph_common.BENCH_PREFIX) ||
      renderInfo.node.name.startsWith(tf_graph_common.NPU_PREFIX)
    ) {
      if (_.isEmpty(matchedNodeLink)) {
        return '#C7C7C7';
      }
    }
    if (overflowLevelItem) {
      switch (overflowLevelItem.value) {
        case 'medium':
          return '#B6C7FC';
        case 'high':
          return '#7E96F0';
        case 'critical':
          return '#4668B8';
        default:
          Notification.show('Unknown overflow level', {
            position: 'middle',
            duration: 1000,
            theme: 'error',
          });
          // 处理未知情况
          return 'transparent';
      }
    } else if (precisionItem) {
      return getColorByPrecisionIndex(precisionItem.value);
    } else {
      return 'transparent';
    }
  } else {
    // Other nodes are white.
    return 'transparent';
  }
}
/**
 * Modify node style by toggling class and assign attributes (only for things
 * that can't be done in css).
 */
export function stylize(
  nodeGroup,
  renderInfo: render.RenderNodeInfo,
  sceneElement: TfGraphScene,
  nodeClassName?,
): void {
  const resolvedNodeClassName = nodeClassName || Class.Node.SHAPE || Class.Node.OUTER;
  const isHighlighted = sceneElement.isNodeHighlighted(renderInfo.node.name);
  const isSelected = sceneElement.isNodeSelected(renderInfo.node.name);
  const isExpanded = renderInfo.expanded && resolvedNodeClassName !== Class.Annotation.NODE;
  const isLinked = sceneElement.isNodeLinked(renderInfo.node.name);
  nodeGroup.classed('highlighted', isHighlighted);
  nodeGroup.classed('selected', isSelected);
  nodeGroup.classed('expanded', isExpanded);
  nodeGroup.classed('linked', isLinked);
  // Main node always exists here and it will be reached before subscene,
  // so d3 selection is fine here.OLOR_TARGET)
  const node = nodeGroup.select(`.${resolvedNodeClassName} .${Class.Node.COLOR_TARGET}`);
  const outerNode = nodeGroup.select(`.${Class.Node.OUTER} .${Class.Node.COLOR_TARGET}`);
  const fillColor = getFillForNode(renderInfo);
  if (
    renderInfo.node.type === tf_graph.NodeType.META ||
    renderInfo.node.type === tf_graph.NodeType.MULTI_COLLECTION ||
    renderInfo.node.type === tf_graph.NodeType.API_LIST
  ) {
    node.style('fill', 'white');
    outerNode.style('fill', fillColor);
  } else {
    node.style('fill', fillColor);
  }
  // Choose outline to be darker version of node color if the node is a single
  // color and is not selected.
  node.style('stroke', isSelected ? null : getStrokeForFill(fillColor === 'transparent' ? 'white' : fillColor));
}
/**
 * Given a node's fill color/gradient, determine the stroke for the node.
 */
export function getStrokeForFill(fill: string): string {
  // If node is colored by a gradient, then use a dark gray outline.
  if (fill.substring(0, 3) === 'url') {
    return render.MetanodeColors.GRADIENT_OUTLINE;
  } else if (fill.startsWith('rgba')) {
    return 'rgb(167, 167, 167)';
  } else {
    return d3.rgb(fill).darker().toString();
  }
}

/**
 * Scene.
 */

/**
 * Select or create a sceneGroup and build/update its nodes and edges.
 *
 * Structure Pattern:
 *
 * <g class='scene'>
 *   <g class='core'>
 *     <g class='edges'>
 *       ... stuff from tf.graph.scene.edges.build ...
 *     </g>
 *     <g class='nodes'>
 *       ... stuff from tf.graph.scene.nodes.build ...
 *     </g>
 *   </g>
 *   <g class='in-extract'>
 *     <g class='nodes'>
 *       ... stuff from tf.graph.scene.nodes.build ...
 *     </g>
 *   </g>
 *   <g class='out-extract'>
 *     <g class='nodes'>
 *       ... stuff from tf.graph.scene.nodes.build ...
 *     </g>
 *   </g>
 * </g>
 *
 * @param container D3 selection of the parent.
 * @param renderNode render node of a metanode or series node.
 * @param sceneElement <tf-graph-scene> polymer element.
 * @param sceneClass class attribute of the scene (default='scene').
 */
export function buildGroupForScene(
  container,
  renderNode: render.RenderGroupNodeInfo,
  sceneElement: TfGraphScene,
  sceneClass?: string,
): void {
  const newSceneClass = sceneClass ?? Class.Scene.GROUP;
  let isNewSceneGroup = selectChild(container, 'g', newSceneClass).empty();
  let sceneGroup = selectOrCreateChild(container, 'g', newSceneClass);
  // core
  let coreGroup = selectOrCreateChild(sceneGroup, 'g', Class.Scene.CORE);
  let coreNodes = _.reduce(
    renderNode.coreGraph.nodes(),
    (nodes, name) => {
      let node = renderNode.coreGraph.node(name);
      nodes.push(node);
      return nodes;
    },
    Array<any>(),
  );
  // Create the layer of nodes for this scene (ellipses, rects etc).
  buildGroup(coreGroup, coreNodes, sceneElement);
  tf_graph_scene.position(sceneGroup, renderNode);
  // Fade in the scene group if it didn't already exist.
  if (isNewSceneGroup) {
    sceneGroup.attr('opacity', 0).transition().attr('opacity', 1);
  }
}
export function getColors(colors): void {
  colorStorage = colors;
}
